package vip.zhenzicheng.nettybasic.echo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 服务端的业务Handler
 *
 * @author zhenzicheng
 * @date 2022-06-06 20:08
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    System.out.println("server accept:" + in.toString(CharsetUtil.UTF_8));
    ctx.writeAndFlush(in); // 将接收的数据重新发送回客户端
    ctx.close(); // 模拟短连接
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
